﻿//------------------------------------------------------------------------------ 
// <copyright file="JValidator.cs" company="Fm Computer">
//     Copyright (c) Fm Computer di Menatti Fulvia.  All rights reserved.
// </copyright>
//----------------------------------------------------------------------------- 
[assembly: System.Web.UI.WebResource("FmjQuery.Controls.Extender.JValidator.validator.css", "text/css")]

namespace FmjQuery
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Text;
    using System.Web.UI;

    /// <summary>
    /// Add confirm question to control
    /// </summary>
    [ToolboxData("<{0}:JValidator runat=server></{0}:JValidator>")]
    [DefaultProperty("TargetControlID")]
    [NonVisualControl]
    public class JValidator : JQueryExtendControl
    {
        #region Fields
        /// <summary>
        /// Collection of validate control
        /// </summary>
        private ValidateControls tcontrols;
        #endregion

        #region Costruct
        /// <summary>
        /// Initializes a new instance of the JValidator class.
        /// </summary>
        public JValidator()
        {
            this.IsRenderControl = false;
        }
        #endregion

        #region Property
        /// <summary>
        /// Gets list of validate control
        /// </summary>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ValidateControls CheckControls
        {
            get
            {
                if (this.tcontrols == null)
                {
                    this.tcontrols = new ValidateControls();
                }

                return this.tcontrols;
            }
        }
        #endregion

        #region Overrides of JQueryExtendControl
        /// <summary>
        /// Return list of webResource
        /// </summary>
        /// <returns>web resources</returns>
        public override JWebSources GetResources()
        {
            return new JWebSources { new JSource(Properties.Settings.Default.Css_Validator_Name, Properties.Settings.Default.Css_Validator_Url, JSourceType.css, true), };
        }

        /// <summary>
        /// Gets list of css image resources
        /// </summary>
        /// <returns>list of images</returns>
        public override CssResources GetCssResources()
        {
            return null;
        }

        /// <summary>
        /// Gets list of client nameSpace
        /// </summary>
        /// <returns>list of namespace</returns>
        public override ClientNameSpaces GetClientNameSpace()
        {
            return new ClientNameSpaces { new ClientNameSpace("Validators", new ClientEnums { new ClientEnum("Types", typeof(ValidationType)), new ClientEnum("VarType", typeof(RangeType)), new ClientEnum("CompareOperator", typeof(CompareOperator)), new ClientEnum("ExtraAlert", typeof(ExtraAlert)) }) };
        }

        /// <summary>
        /// Create jQuery control
        /// </summary>
        public override void CreateJControl()
        {
            Manager.Validator = true;

            if (this.Enabled)
            {
                // create script
                StringBuilder builder = new StringBuilder();

                builder.AppendFormat("$('#{0}').CreateValidator()", this.TargetControlClientID);

                foreach (ValidateControl control in this.CheckControls)
                {
                    builder.AppendFormat(".AddValidation({0},'{1}',", (int) control.Type, control.IsClientControl ? control.IDControl : FindControl(control.IDControl).ClientID);
                    builder.Append("{");
                    builder.AppendFormat("cssClass: '{0}'", !string.IsNullOrEmpty(control.CssClass) ? control.CssClass : "notValidControl");
                    builder.AppendFormat(",extraCss: '{0}'", !string.IsNullOrEmpty(control.ExtraCss) ? control.ExtraCss : "notValidExtraControl");

                    switch (control.Type)
                    {
                        case ValidationType.Length:
                            {
                                if (!string.IsNullOrEmpty(control.Minimun))
                                {
                                    builder.AppendFormat(",min: {0}", control.Minimun);
                                }

                                if (!string.IsNullOrEmpty(control.Maximun))
                                {
                                    builder.AppendFormat(",max: {0}", control.Maximun);
                                }

                                break;
                            }

                        case ValidationType.Compare:
                            {
                                if (!string.IsNullOrEmpty(control.CompareValue))
                                {
                                    builder.AppendFormat(",value: '{0}'", control.CompareValue);
                                }
                                else
                                {
                                    if (string.IsNullOrEmpty(control.CompareControlID))
                                    {
                                        throw new InvalidOperationException("Must insert CompareValue or CompareControlID for use CompareValidator");
                                    }

                                    builder.AppendFormat(",cmpIDControl: '{0}'", control.IsCompareControlClient ? control.CompareControlID : FindControl(control.CompareControlID).ClientID);
                                }

                                builder.AppendFormat(",cmpOp: {0}", (int) control.CompareType);

                                break;
                            }

                        case ValidationType.Range:
                            {
                                if (!string.IsNullOrEmpty(control.Minimun))
                                {
                                    builder.AppendFormat(",min: {0}", control.Minimun);
                                }

                                if (!string.IsNullOrEmpty(control.Maximun))
                                {
                                    builder.AppendFormat(",max: {0}", control.Maximun);
                                }

                                builder.AppendFormat(",varType: {0}", (int) control.TypeRange);
                                break;
                            }

                        case ValidationType.RegularExpression:
                            {
                                if (string.IsNullOrEmpty(control.RegularExpression))
                                {
                                    throw new InvalidOperationException("Must insert RegularExpression for user RegexValidator");
                                }

                                builder.AppendFormat(",regex: /{0}/", control.RegularExpression);

                                break;
                            }
                    }

                    if (control.TypeExtraAlert.HasValue)
                    {
                        builder.AppendFormat(",extraAlert: {0}", (int) control.TypeExtraAlert.Value);
                    }

                    builder.Append("})");
                }

                builder.Append(";");

                Utility.RegisterStartUpScript(this.Page, string.Concat("Validator_", this.ClientID), builder.ToString());
            }
        }
        #endregion

        #region Public Method

        /// <summary>
        /// Remove control from list validation
        /// </summary>
        /// <param name="idControl">code of control</param>
        public void RemoveValidation(string idControl)
        {
            this.RemoveValidation(new List<string> { idControl });
        }

        /// <summary>
        /// Remove al control into list from validation list
        /// </summary>
        /// <param name="listIdControl">list of control code</param>
        public void RemoveValidation(IEnumerable<string> listIdControl)
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendFormat("$('#{0}')", this.TargetControlClientID);

            foreach (string s in listIdControl)
            {
                builder.AppendFormat(".RemoveValidation('{0}')", FindControl(s).ClientID);
            }

            builder.Append(";");

            string script = builder.ToString();

            if (script.Contains(".RemoveValidation("))
            {
                Utility.RegisterStartUpScript(this.Page, string.Concat("RemoveValidation_", this.ClientID), script);
            }
        }
        #endregion
    }
}
